<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

// 图表实例
const chartRef = ref<HTMLDivElement>()
let chartInstance: echarts.ECharts | null = null

// 数据存储
const maxDataPoints = 60 // 最多保存1小时的数据（每分钟1个点）
const timeData = ref<string[]>([])
const throughputData = ref<number[]>([]) // 修改为吞吐量数据
const energyData = ref<number[]>([])
const efficiencyData = ref<number[]>([])

// 历史数据模式
const isHistoryMode = ref(false)
const selectedHour = ref<number | null>(null)

// API配置
const API_BASE_URL = '/basestation-api' // 使用代理路径，避免跨域问题

// 定时器
let dataTimer: number | null = null
let initialTimer: number | null = null // 用于初始等待到整分钟的定时器

// 获取当前时间的秒数（从当天0点开始），取整到分钟
const getCurrentTimeSeconds = (): number => {
  const now = new Date()
  const totalSeconds = now.getHours() * 3600 + now.getMinutes() * 60
  return totalSeconds // 只取到分钟，秒数为0
}

// 检查是否在0点-1点之间
const isInFirstHour = (): boolean => {
  const now = new Date()
  return now.getHours() === 0
}

// 获取可用的最大数据点数（0点-1点之间受限制）
const getMaxAvailableDataPoints = (): number => {
  if (isInFirstHour()) {
    const now = new Date()
    const minutesPassedToday = now.getMinutes()
    return Math.min(minutesPassedToday + 1, 60) // 最多到当前分钟
  }
  return 60 // 其他时间可以查看完整的60分钟
}

// 缩放状态管理
const zoomState = ref({
  start: 75, // 默认显示最近15分钟（75%开始）
  end: 100,
  userModified: false // 标记用户是否手动调整过缩放
})

// 防抖同步状态
let syncTimeout: number | null = null
const isSyncing = ref(false)

// 显示模式管理
const displayMode = ref<'combined' | 'separated'>('combined')

// 独立图表的实例
const throughputChartRef = ref<HTMLDivElement>()
const energyChartRef = ref<HTMLDivElement>()
const efficiencyChartRef = ref<HTMLDivElement>()
let throughputChartInstance: echarts.ECharts | null = null
let energyChartInstance: echarts.ECharts | null = null
let efficiencyChartInstance: echarts.ECharts | null = null

// 从后端获取图表数据
const fetchChartData = async (start: number, end: number): Promise<any> => {
  try {
    const url = `${API_BASE_URL}/getchartdata?start=${start}&end=${end}&dataname=total_power_his`
    console.log(`🔍 正在获取图表数据: start=${start}, end=${end}`)
    console.log(`🔍 请求URL: ${url}`)
    console.log(`🔍 时间范围: ${Math.floor(start/3600)}:${Math.floor((start%3600)/60).toString().padStart(2,'0')}:${(start%60).toString().padStart(2,'0')} - ${Math.floor(end/3600)}:${Math.floor((end%3600)/60).toString().padStart(2,'0')}:${(end%60).toString().padStart(2,'0')}`)
    
    const response = await fetch(url)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const data = await response.json()
    console.log('🔍 获取到的图表数据:', data)
    console.log('🔍 数据结构检查:', {
      hasRegAverThroughput: !!data?.reg_aver_throughput_his,
      hasTotalPower: !!data?.total_power_his,
      throughputLength: data?.reg_aver_throughput_his?.length || 0,
      powerLength: data?.total_power_his?.length || 0
    })
    return data
  } catch (error) {
    console.error('❌ 获取图表数据失败:', error)
    return null
  }
}

// 获取历史数据（按小时）
const fetchHistoryData = async (hour: number): Promise<void> => {
  const startTime = hour * 3600 // 小时开始时间
  const endTime = startTime + 3600 - 60 // 小时结束时间，减去60秒确保不超出小时边界
  
  console.log(`获取历史数据: 第${hour}小时`)
  console.log(`时间范围: ${startTime}-${endTime}秒 (${hour}:00:00 - ${hour}:59:00)`)
  
  try {
    const data = await fetchChartData(startTime, endTime)
    if (data && (data.reg_aver_throughput_his || data.total_power_his)) {
      // 清空当前数据
      timeData.value = []
      throughputData.value = []
      energyData.value = []
      efficiencyData.value = []
      
      // 处理历史数据，按分钟间隔显示
      const throughputHis = data.reg_aver_throughput_his || []
      const powerHis = data.total_power_his || []
      
      console.log(`历史数据长度: throughput=${throughputHis.length}, power=${powerHis.length}`)
      console.log(`API请求范围: ${startTime}-${endTime}秒`)
      
      // API返回的应该是60个数据点（hour:00 到 hour:59，每分钟一个）
      // 生成时间标签和对应数据
      for (let minute = 0; minute < 60; minute++) {
        const timeInSeconds = startTime + minute * 60
        const hourPart = Math.floor(timeInSeconds / 3600)
        const minutePart = Math.floor((timeInSeconds % 3600) / 60)
        const timeLabel = `${hourPart.toString().padStart(2, '0')}:${minutePart.toString().padStart(2, '0')}:00`
        
        // 直接使用数组索引获取数据，API返回的数据按时间顺序排列
        const throughput = minute < throughputHis.length ? throughputHis[minute] : 0
        const energy = minute < powerHis.length ? (powerHis[minute] / 1000) : 0 // 转换为kWh（原始数据除以1000）
        const efficiency = energy > 0 ? throughput / energy : 0
        
        timeData.value.push(timeLabel)
        throughputData.value.push(throughput)
        energyData.value.push(energy)
        efficiencyData.value.push(efficiency)
      }
      
      console.log(`历史数据加载完成: ${timeData.value.length}个数据点`)
      
      // 重置缩放状态，显示全部历史数据
      zoomState.value.start = 0
      zoomState.value.end = 100
      zoomState.value.userModified = false
      
      // 更新图表
      updateChart()
    } else {
      console.warn('历史数据为空，生成模拟数据')
      generateHistoryMockData(hour)
    }
  } catch (error) {
    console.error('获取历史数据失败:', error)
    generateHistoryMockData(hour)
  }
}

// 生成历史模拟数据
const generateHistoryMockData = (hour: number) => {
  timeData.value = []
  throughputData.value = []
  energyData.value = []
  efficiencyData.value = []
  
  for (let minute = 0; minute < 60; minute++) {
    const timeLabel = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00`
    const throughput = 2 + Math.random() * 3
    const energy = 5 + Math.random() * 0.5
    const efficiency = throughput / energy
    
    timeData.value.push(timeLabel)
    throughputData.value.push(throughput)
    energyData.value.push(energy)
    efficiencyData.value.push(efficiency)
  }
  
  zoomState.value.start = 0
  zoomState.value.end = 100
  zoomState.value.userModified = false
  
  updateChart()
}

// 更新数据
const updateData = async () => {
  console.log('===== updateData 被调用 =====')
  console.log('当前模式:', isHistoryMode.value ? '历史模式' : '实时模式')
  console.log('当前数据点数量:', timeData.value.length)
  
  // 如果处于历史模式，不进行实时更新
  if (isHistoryMode.value) {
    console.log('当前处于历史模式，跳过实时更新')
    return
  }
  
  const currentTime = getCurrentTimeSeconds()
  // 请求当前分钟的数据（整分钟时刻的单点数据）
  const currentMinuteStart = Math.floor(currentTime / 60) * 60 // 当前分钟的开始时刻
  
  console.log(`更新数据: 当前时间=${currentTime}, 请求数据时刻=${currentMinuteStart} (${Math.floor(currentMinuteStart/3600)}:${Math.floor((currentMinuteStart%3600)/60).toString().padStart(2,'0')})`)
  
  try {
    // 请求单个时刻的数据
    const data = await fetchChartData(currentMinuteStart, currentMinuteStart)
    if (data && (data.reg_aver_throughput_his || data.total_power_his)) {
      // 生成整分钟的时间标签
      const timeDate = new Date()
      timeDate.setHours(0, 0, 0, 0) // 设置为当天0点
      timeDate.setSeconds(currentMinuteStart) // 加上秒数
      const time = timeDate.toLocaleTimeString()
      
      console.log(`生成的时间标签: ${time} (对应秒数: ${currentMinuteStart})`)
      
      console.log('API返回的数据结构:', {
        reg_aver_throughput_his: data.reg_aver_throughput_his?.length || 0,
        total_power_his: data.total_power_his?.length || 0
      })
      
      // 获取数据（应该只有一个数据点）
      const throughput = data.reg_aver_throughput_his?.[0] || 0
      const energy = ((data.total_power_his?.[0] || 0) / 1000) // 转换为kWh
      
      console.log(`解析的数据: 平均吞吐量=${throughput}, 能耗=${energy}kWh`)
      
      // 计算能效比
      const efficiency = energy > 0 ? throughput / energy : 0
      
      // 检查是否是重复的时间点（避免重复添加）
      const lastTimeIndex = timeData.value.length - 1
      if (lastTimeIndex >= 0) {
        const lastTimeSeconds = getTimeSeconds(timeData.value[lastTimeIndex])
        console.log(`检查重复: 最后时间=${timeData.value[lastTimeIndex]}(${lastTimeSeconds}s), 当前时间=${time}(${currentMinuteStart}s)`)
        
        if (lastTimeSeconds === currentMinuteStart) {
          console.log('⚠️ 检测到重复时间点，跳过添加')
          return
        }
      }
      
      // 添加新数据
      timeData.value.push(time)
      throughputData.value.push(throughput)
      energyData.value.push(energy)
      efficiencyData.value.push(efficiency)
      
      console.log(`✅ 添加新数据: 时间=${time}, 平均吞吐量=${throughput}, 能耗=${energy}kWh, 能效比=${efficiency}`)
      
      // 保持数据点数量在限制内，移除最早的数据
      const currentMaxPoints = Math.min(maxDataPoints, getMaxAvailableDataPoints())
      if (timeData.value.length > currentMaxPoints) {
        const removeCount = timeData.value.length - currentMaxPoints
        for (let i = 0; i < removeCount; i++) {
          const removedTime = timeData.value.shift()
          throughputData.value.shift()
          energyData.value.shift()
          efficiencyData.value.shift()
          console.log(`🗑️ 移除最早数据点: ${removedTime}`)
        }
        console.log(`数据点超出限制，移除了 ${removeCount} 个点，当前限制: ${currentMaxPoints}`)
      }
      
      // 如果用户没有手动调整过缩放，则自动滚动到最新15分钟数据
      if (!zoomState.value.userModified) {
        // 当数据点数量 >= 15时，始终显示最后15个数据点
        if (timeData.value.length >= 15) {
          const newStart = Math.max(0, ((timeData.value.length - 15) / timeData.value.length) * 100)
          zoomState.value.start = newStart
          zoomState.value.end = 100
          console.log(`自动滚动到最新15分钟: start=${newStart.toFixed(1)}%, end=100%`)
        }
      }
      
      // 更新图表
      updateChart()
    } else {
      console.warn('API返回的数据为空或格式不正确，使用模拟数据')
      addMockDataPoint(currentMinuteStart)
    }
  } catch (error) {
    console.error('更新数据失败:', error)
    // 如果API调用失败，使用模拟数据
    addMockDataPoint(currentMinuteStart)
  }
  
  console.log('===== updateData 执行完成 =====')
}

// 添加模拟数据点（作为备用）
const addMockDataPoint = (timeSeconds: number) => {
  // 生成整分钟的时间标签
  const timeDate = new Date()
  timeDate.setHours(0, 0, 0, 0)
  timeDate.setSeconds(timeSeconds)
  const time = timeDate.toLocaleTimeString()
  
  // 模拟数据
  const throughput = 2 + Math.random() * 3
  const energy = 5 + Math.random() * 0.5
  const efficiency = throughput / energy
  
  // 检查重复
  const lastTimeIndex = timeData.value.length - 1
  if (lastTimeIndex >= 0) {
    const lastTimeSeconds = getTimeSeconds(timeData.value[lastTimeIndex])
    if (lastTimeSeconds === timeSeconds) {
      console.log('⚠️ 检测到重复时间点（模拟数据），跳过添加')
      return
    }
  }
  
  timeData.value.push(time)
  throughputData.value.push(throughput)
  energyData.value.push(energy)
  efficiencyData.value.push(efficiency)
  
  console.log(`📊 使用模拟数据: 时间=${time}, 平均吞吐量=${throughput}, 能耗=${energy}kWh, 能效比=${efficiency}`)
  
  // 保持数据点数量限制
  const currentMaxPoints = Math.min(maxDataPoints, getMaxAvailableDataPoints())
  if (timeData.value.length > currentMaxPoints) {
    const removeCount = timeData.value.length - currentMaxPoints
    for (let i = 0; i < removeCount; i++) {
      const removedTime = timeData.value.shift()
      throughputData.value.shift()
      energyData.value.shift()
      efficiencyData.value.shift()
      console.log(`🗑️ 移除最早数据点: ${removedTime}`)
    }
  }
  
  // 自动滚动逻辑
  if (!zoomState.value.userModified && timeData.value.length >= 15) {
    const newStart = Math.max(0, ((timeData.value.length - 15) / timeData.value.length) * 100)
    zoomState.value.start = newStart
    zoomState.value.end = 100
  }
  
  updateChart()
}

// 辅助函数：从时间字符串获取秒数
const getTimeSeconds = (timeStr: string): number => {
  const parts = timeStr.split(':')
  if (parts.length >= 3) {
    const hours = parseInt(parts[0])
    const minutes = parseInt(parts[1])
    const seconds = parseInt(parts[2])
    return hours * 3600 + minutes * 60 + seconds
  }
  return 0
}



// 更新图表
const updateChart = () => {
  console.log('正在更新图表...', {
    displayMode: displayMode.value,
    dataLength: timeData.value.length,
    lastThroughput: throughputData.value[throughputData.value.length - 1],
    lastEnergy: energyData.value[energyData.value.length - 1]
  })
  
  if (displayMode.value === 'combined') {
    updateCombinedChart()
  } else {
    updateSeparatedCharts()
  }
}

// 更新合并图表
const updateCombinedChart = () => {
  if (!chartInstance) {
    console.warn('图表实例不存在')
    return
  }
  
  console.log('更新合并图表，数据长度:', {
    time: timeData.value.length,
    throughput: throughputData.value.length,
    energy: energyData.value.length,
    efficiency: efficiencyData.value.length
  })
  
  const option = {
    animation: true,
    animationDuration: 500,
    animationEasing: 'cubicOut' as const,
    title: {
      text: '基站实时监控总览',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function(params: any) {
        let result = `时间: ${params[0].axisValue}<br/>`
        params.forEach((param: any) => {
          const unit = param.seriesName === '平均吞吐量' ? ' Mbps' : 
                      param.seriesName === '能耗' ? ' kWh' : ''
          // 根据不同指标显示不同精度
          const precision = param.seriesName === '能效比' ? 4 : 3
          result += `${param.marker}${param.seriesName}: ${param.value.toFixed(precision)}${unit}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['平均吞吐量', '能耗', '能效比'],
      top: 45,
      left: 'center'
    },
    grid: {
      left: '8%',
      right: '8%',
      bottom: '8%',
      top: '20%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {
          title: '保存为图片'
        },
        dataZoom: {
          title: {
            zoom: '区域缩放',
            back: '缩放还原'
          }
        },
        restore: {
          title: '还原'
        }
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeData.value,
      axisLabel: {
        interval: 29, // 每30秒显示一个标签
        rotate: 0,
        formatter: function(value: string) {
          // 只显示时:分:秒，去掉毫秒
          return value.split('.')[0]
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      splitNumber: 8 // 增加分割线数量，更好地显示变化
    },
    yAxis: [
      {
        type: 'value',
        name: '平均吞吐量(Mbps)/能耗(kWh)',
        nameLocation: 'middle',
        nameGap: 50,
        nameTextStyle: {
          fontSize: 12,
          color: '#666'
        },
        position: 'left',
        scale: true,
        min: function(value: any) {
          // 动态计算最小值，保留一定的缓冲区间以显示变化
          const buffer = (value.max - value.min) * 0.1 || 0.5
          return Math.max(0, value.min - buffer)
        },
        max: function(value: any) {
          // 动态计算最大值，保留一定的缓冲区间以显示变化
          const buffer = (value.max - value.min) * 0.1 || 0.5
          return value.max + buffer
        },
        interval: function(value: any) {
          // 动态计算间隔，确保有足够的刻度显示变化
          const range = value.max - value.min
          return range / 8 // 将Y轴分为8个区间
        },
        axisLabel: {
          formatter: function(value: number) {
            return value.toFixed(2)
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#f0f0f0',
            type: 'dashed',
            width: 1
          }
        },
        splitNumber: 8
      },
      {
        type: 'value',
        name: '能效比',
        nameLocation: 'middle',
        nameGap: 50,
        nameTextStyle: {
          fontSize: 12,
          color: '#666'
        },
        position: 'right',
        scale: true,
        min: function(value: any) {
          // 能效比的动态最小值
          const buffer = (value.max - value.min) * 0.1 || 0.1
          return Math.max(0, value.min - buffer)
        },
        max: function(value: any) {
          // 能效比的动态最大值
          const buffer = (value.max - value.min) * 0.1 || 0.1
          return value.max + buffer
        },
        interval: function(value: any) {
          // 能效比的动态间隔
          const range = value.max - value.min
          return range / 6 // 将Y轴分为6个区间
        },
        axisLabel: {
          formatter: function(value: number) {
            return value.toFixed(3)
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#e0e0e0',
            type: 'dashed',
            width: 1
          }
        },
        splitNumber: 6
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        start: zoomState.value.start,
        end: zoomState.value.end,
        filterMode: 'filter',
        moveOnMouseMove: true,
        zoomOnMouseWheel: true
      },
      {
        start: zoomState.value.start,
        end: zoomState.value.end,
        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23.1h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
        handleSize: '80%',
        handleStyle: {
          color: '#fff',
          shadowBlur: 3,
          shadowColor: 'rgba(0, 0, 0, 0.6)',
          shadowOffsetX: 2,
          shadowOffsetY: 2
        },
        textStyle: {
          color: '#999'
        },
        borderColor: '#ddd'
      }
    ],
    series: [
      {
        name: '平均吞吐量',
        type: 'line',
        yAxisIndex: 0,
        data: throughputData.value,
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        lineStyle: {
          color: '#5470c6',
          width: 2
        },
        itemStyle: {
          color: '#5470c6'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
            { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
          ])
        }
      },
      {
        name: '能耗',
        type: 'line',
        yAxisIndex: 0,
        data: energyData.value,
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        lineStyle: {
          color: '#fc8452',
          width: 2
        },
        itemStyle: {
          color: '#fc8452'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(252, 132, 82, 0.3)' },
            { offset: 1, color: 'rgba(252, 132, 82, 0.1)' }
          ])
        }
      },
      {
        name: '能效比',
        type: 'line',
        yAxisIndex: 1,
        data: efficiencyData.value,
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        lineStyle: {
          color: '#91cc75',
          width: 2
        },
        itemStyle: {
          color: '#91cc75'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(145, 204, 117, 0.3)' },
            { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
          ])
        }
      }
    ]
  }
  
  chartInstance.setOption(option, false, true)
}

// 更新独立图表
const updateSeparatedCharts = () => {
  // 使用 requestAnimationFrame 来优化更新时机
  requestAnimationFrame(() => {
    updateThroughputChart()
    updateEnergyChart()
    updateEfficiencyChart()
  })
}

// 创建基础配置
const createBaseChartOption = (title: string, yAxisName: string) => ({
  animation: true,
  animationDuration: 500,
  animationEasing: 'cubicOut' as const,
  title: {
    text: title,
    left: 'center',
    top: 10,
    textStyle: {
      fontSize: 14,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
    formatter: function(params: any) {
      if (params && params.length > 0) {
        const param = params[0]
        const precision = yAxisName.includes('能效比') ? 4 : 3
        const unit = yAxisName.includes('Mbps') ? ' Mbps' : 
                    yAxisName.includes('kWh') ? ' kWh' : ''
        return `时间: ${param.axisValue}<br/>${param.marker}${param.seriesName}: ${param.value.toFixed(precision)}${unit}`
      }
      return ''
    }
  },
  grid: {
    left: '10%',
    right: '10%',
    bottom: '15%',
    top: '25%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: timeData.value,
    axisLabel: {
      interval: 29,
      rotate: 0,
      formatter: function(value: string) {
        return value.split('.')[0]
      }
    }
  },
  yAxis: {
    type: 'value',
    name: yAxisName,
    nameLocation: 'middle',
    nameGap: 40,
    nameTextStyle: {
      fontSize: 12,
      color: '#666'
    },
    scale: true,
    min: function(value: any) {
      // 动态计算最小值，保留缓冲区间以显示变化
      const buffer = (value.max - value.min) * 0.15 || 0.5
      return Math.max(0, value.min - buffer)
    },
    max: function(value: any) {
      // 动态计算最大值，保留缓冲区间以显示变化
      const buffer = (value.max - value.min) * 0.15 || 0.5
      return value.max + buffer
    },
    interval: function(value: any) {
      // 动态计算间隔，确保有足够的刻度显示变化
      const range = value.max - value.min
      return range / 8 // 将Y轴分为8个区间
    },
    axisLabel: {
      formatter: function(value: number) {
        // 根据不同的指标设置不同的精度
        if (yAxisName.includes('能效比')) {
          return value.toFixed(3)
        } else {
          return value.toFixed(2)
        }
      }
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: '#f0f0f0',
        type: 'dashed',
        width: 1
      }
    },
    splitNumber: 8
  },
  dataZoom: [
    {
      type: 'inside',
      start: zoomState.value.start,
      end: zoomState.value.end,
      filterMode: 'filter',
      throttle: 100 // 添加节流，减少更新频率
    },
    {
      start: zoomState.value.start,
      end: zoomState.value.end,
      height: 20,
      bottom: 10,
      throttle: 100, // 添加节流
      moveHandleSize: 8, // 减小手柄大小，提高性能
      handleSize: '60%' // 减小手柄大小
    }
  ]
})

// 更新吞吐量图表
const updateThroughputChart = () => {
  if (!throughputChartInstance) return
  
  const option = {
    ...createBaseChartOption('平均吞吐量', '平均吞吐量 (Mbps)'),
    series: [{
      name: '平均吞吐量',
      type: 'line',
      data: throughputData.value,
      smooth: true,
      symbol: 'circle',
      symbolSize: 3,
      lineStyle: {
        color: '#5470c6',
        width: 2
      },
      itemStyle: {
        color: '#5470c6'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
          { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
        ])
      }
    }]
  }
  
  throughputChartInstance.setOption(option, {
    notMerge: false,
    lazyUpdate: true // 启用懒更新
  })
}

// 更新能耗图表
const updateEnergyChart = () => {
  if (!energyChartInstance) return
  
  const option = {
    ...createBaseChartOption('能耗', '能耗 (kWh)'),
    series: [{
      name: '能耗',
      type: 'line',
      data: energyData.value,
      smooth: true,
      symbol: 'circle',
      symbolSize: 3,
      lineStyle: {
        color: '#fc8452',
        width: 2
      },
      itemStyle: {
        color: '#fc8452'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(252, 132, 82, 0.3)' },
          { offset: 1, color: 'rgba(252, 132, 82, 0.1)' }
        ])
      }
    }]
  }
  
  energyChartInstance.setOption(option, {
    notMerge: false,
    lazyUpdate: true
  })
}

// 更新能效比图表
const updateEfficiencyChart = () => {
  if (!efficiencyChartInstance) return
  
  const option = {
    ...createBaseChartOption('能效比', '能效比'),
    series: [{
      name: '能效比',
      type: 'line',
      data: efficiencyData.value,
      smooth: true,
      symbol: 'circle',
      symbolSize: 3,
      lineStyle: {
        color: '#91cc75',
        width: 2
      },
      itemStyle: {
        color: '#91cc75'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(145, 204, 117, 0.3)' },
          { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
        ])
      }
    }]
  }
  
  efficiencyChartInstance.setOption(option, {
    notMerge: false,
    lazyUpdate: true
  })
}

// 切换显示模式
const toggleDisplayMode = () => {
  displayMode.value = displayMode.value === 'combined' ? 'separated' : 'combined'
}

// 初始化合并图表
const initCombinedChart = () => {
  if (!chartRef.value) return
  
  // 如果已经存在实例，先销毁
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  
  chartInstance = echarts.init(chartRef.value)
  
  // 监听dataZoom事件，检测用户手动调整
  chartInstance.on('dataZoom', (params: any) => {
    if (params.batch) {
      // 处理批量缩放事件
      params.batch.forEach((item: any) => {
        if (item.start !== undefined && item.end !== undefined) {
          zoomState.value.start = item.start
          zoomState.value.end = item.end
          zoomState.value.userModified = true
        }
      })
    } else {
      // 处理单个缩放事件
      if (params.start !== undefined && params.end !== undefined) {
        zoomState.value.start = params.start
        zoomState.value.end = params.end
        zoomState.value.userModified = true
      }
    }
  })
  
  // 立即更新图表
  updateCombinedChart()
}

// 初始化独立图表
const initSeparatedCharts = () => {
  // 清理并重新初始化吞吐量图表
  if (throughputChartInstance) {
    throughputChartInstance.dispose()
    throughputChartInstance = null
  }
  if (throughputChartRef.value) {
    throughputChartInstance = echarts.init(throughputChartRef.value)
  }
  
  // 清理并重新初始化能耗图表
  if (energyChartInstance) {
    energyChartInstance.dispose()
    energyChartInstance = null
  }
  if (energyChartRef.value) {
    energyChartInstance = echarts.init(energyChartRef.value)
  }
  
  // 清理并重新初始化能效比图表
  if (efficiencyChartInstance) {
    efficiencyChartInstance.dispose()
    efficiencyChartInstance = null
  }
  if (efficiencyChartRef.value) {
    efficiencyChartInstance = echarts.init(efficiencyChartRef.value)
  }
  
  // 为独立图表添加事件监听
  const chartInstances = [throughputChartInstance, energyChartInstance, efficiencyChartInstance]
  chartInstances.forEach(instance => {
    if (instance) {
      instance.on('dataZoom', (params: any) => {
        if (isSyncing.value) return // 如果正在同步中，跳过
        
        if (params.start !== undefined && params.end !== undefined) {
          zoomState.value.start = params.start
          zoomState.value.end = params.end
          zoomState.value.userModified = true
          
          // 同步其他独立图表的缩放
          debouncedSyncCharts(instance, params.start, params.end)
        }
      })
      
      // 添加datazoom开始事件，暂停数据更新
      instance.on('datazoom', () => {
        // 缩放时可以暂停实时更新来提升性能
      })
    }
  })
  
  updateSeparatedCharts()
}

// 防抖同步其他图表
const debouncedSyncCharts = (sourceInstance: echarts.ECharts, start: number, end: number) => {
  if (syncTimeout) {
    clearTimeout(syncTimeout)
  }
  
  syncTimeout = window.setTimeout(() => {
    if (isSyncing.value) return
    
    isSyncing.value = true
    
    const chartInstances = [throughputChartInstance, energyChartInstance, efficiencyChartInstance]
    chartInstances.forEach(chart => {
      if (chart && chart !== sourceInstance) {
        try {
          chart.dispatchAction({
            type: 'dataZoom',
            start: start,
            end: end,
            silent: true // 静默更新，不触发事件
          })
        } catch (error) {
          console.warn('同步图表缩放失败:', error)
        }
      }
    })
    
    setTimeout(() => {
      isSyncing.value = false
    }, 50)
  }, 100) // 100ms防抖延迟
}

// 切换历史模式
const toggleHistoryMode = async () => {
  if (isHistoryMode.value) {
    // 切换到实时模式
    console.log('切换到实时模式')
    isHistoryMode.value = false
    selectedHour.value = -1
    
    // 清空现有数据
    timeData.value = []
    throughputData.value = []
    energyData.value = []
    efficiencyData.value = []
    
    // 重新初始化实时数据
    await initChart()
  } else {
    // 切换到历史模式
    console.log('切换到历史模式')
    isHistoryMode.value = true
    // 停止定时器
    stopDataUpdate()
    
    // 默认显示最近的完整小时（当前小时-1）
    const currentHour = new Date().getHours()
    const defaultHour = Math.max(0, currentHour - 1) // 确保不小于0
    selectedHour.value = defaultHour
    
    console.log(`默认选择小时: ${defaultHour} (当前小时: ${currentHour})`)
    
    if (defaultHour >= 0) {
      await fetchHistoryData(defaultHour)
    } else {
      console.warn('当前是0点，没有可用的历史数据')
      // 如果是凌晨0点，生成空数据或提示
      timeData.value = []
      throughputData.value = []
      energyData.value = []
      efficiencyData.value = []
      updateChart()
    }
  }
}

// 选择历史小时
const selectHistoryHour = async (hour: number | null) => {
  if (isHistoryMode.value && hour !== null) {
    selectedHour.value = hour
    await fetchHistoryData(hour)
  }
}

// 停止数据更新
const stopDataUpdate = () => {
  if (dataTimer) {
    clearInterval(dataTimer)
    dataTimer = null
  }
  if (initialTimer) {
    clearTimeout(initialTimer)
    initialTimer = null
  }
}

// 开始数据更新
const startDataUpdate = () => {
  if (!dataTimer && !isHistoryMode.value) {
    const now = new Date()
    const currentMinute = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), 0, 0)
    
    // 计算下一次需要更新数据的分钟
    const nextUpdateMinute = new Date(currentMinute.getTime() + 60 * 1000) // 下一分钟
    
    // 检查当前数据中最新的时间
    const lastTimeInData = timeData.value.length > 0 ? timeData.value[timeData.value.length - 1] : null
    
    console.log('当前时间:', now.toLocaleTimeString())
    console.log('当前整分钟:', currentMinute.toLocaleTimeString())
    console.log('数据中最新时间:', lastTimeInData)
    console.log('下一次更新分钟:', nextUpdateMinute.toLocaleTimeString())
    
    // 计算到下一次更新分钟的毫秒数
    const millisecondsToNextUpdate = nextUpdateMinute.getTime() - now.getTime()
    
    console.log(`将在${millisecondsToNextUpdate}毫秒后（${(millisecondsToNextUpdate/1000).toFixed(1)}秒）开始定时更新`)
    
    // 等待到下一个需要更新的分钟
    initialTimer = window.setTimeout(() => {
      console.log('到达更新时刻，执行第一次更新并开始定时更新')
      updateData() // 执行更新
      dataTimer = window.setInterval(() => {
        console.log('定时更新触发，当前时间:', new Date().toLocaleTimeString())
        updateData()
      }, 60000) // 然后每60秒更新一次
    }, millisecondsToNextUpdate)
  }
}

// 获取可选择的小时列表（当天内）
const getAvailableHours = () => {
  const hours = []
  const currentHour = new Date().getHours()
  
  // 历史模式只能查看已经完整结束的小时
  // 如果当前是19:55，只能查看到18:00-19:00，不能查看当前进行中的19:00-20:00
  const maxAvailableHour = currentHour - 1
  
  console.log(`当前小时: ${currentHour}, 历史模式最大可查看小时: ${maxAvailableHour}`)
  
  for (let i = 0; i <= maxAvailableHour; i++) {
    hours.push({
      value: i,
      label: `${i.toString().padStart(2, '0')}:00-${(i + 1).toString().padStart(2, '0')}:00`
    })
  }
  
  return hours.reverse() // 最新的在前面
}



// 重置缩放到默认15分钟视图
const resetZoomToDefault = () => {
  console.log('重置缩放到默认15分钟视图')
  zoomState.value.userModified = false
  
  // 重新计算15分钟视图的位置
  if (timeData.value.length >= 15) {
    const newStart = Math.max(0, ((timeData.value.length - 15) / timeData.value.length) * 100)
    zoomState.value.start = newStart
    zoomState.value.end = 100
    console.log(`重置缩放: start=${newStart.toFixed(1)}%, end=100%`)
  } else {
    zoomState.value.start = 0
    zoomState.value.end = 100
  }
  
  updateChart()
}

// 初始化图表（首次加载时调用）
const initChart = async () => {
  console.log('开始初始化图表...')
  
  // 如果处于历史模式，不执行实时初始化
  if (isHistoryMode.value) {
    console.log('当前处于历史模式，跳过实时初始化')
    return
  }
  
  // 获取可用的最大数据点数
  const maxAvailablePoints = getMaxAvailableDataPoints()
  console.log(`当前可用的最大数据点数: ${maxAvailablePoints}`)
  
  // 获取当前时间的秒数
  const currentTimeSeconds = getCurrentTimeSeconds()
  const currentMinuteStart = Math.floor(currentTimeSeconds / 60) * 60 // 当前分钟的开始
  
  // 计算需要请求的时间范围：从最早需要的数据到当前分钟
  const startTime = currentMinuteStart - (maxAvailablePoints - 1) * 60 // 往前推maxAvailablePoints-1分钟
  const endTime = currentTimeSeconds
  
  console.log(`初始化时间范围: start=${startTime}, end=${endTime} (${maxAvailablePoints}个数据点)`)
  console.log(`时间范围详情: ${Math.floor(startTime/3600)}:${Math.floor((startTime%3600)/60).toString().padStart(2,'0')} - ${Math.floor(endTime/3600)}:${Math.floor((endTime%3600)/60).toString().padStart(2,'0')}`)
  
  try {
    // 从后端获取初始历史数据
    console.log('从后端获取初始历史数据...')
    const data = await fetchChartData(startTime, endTime)
    
    if (data && (data.reg_aver_throughput_his || data.total_power_his)) {
      console.log('✅ 成功获取初始真实数据')
      
      // 处理返回的数据
      const throughputHis = data.reg_aver_throughput_his || []
      const powerHis = data.total_power_his || []
      
      console.log(`初始数据长度: throughput=${throughputHis.length}, power=${powerHis.length}`)
      
      // 生成时间标签和对应数据
      for (let i = 0; i < maxAvailablePoints; i++) {
        const timeInSeconds = startTime + i * 60 // 每分钟一个数据点
        
        // 生成时间标签
        const timeDate = new Date()
        timeDate.setHours(0, 0, 0, 0) // 设置为当天0点
        timeDate.setSeconds(timeInSeconds) // 加上秒数
        const timeLabel = timeDate.toLocaleTimeString()
        
        // 获取对应的数据（如果数据不够，用最后一个值或0填充）
        const throughput = i < throughputHis.length ? throughputHis[i] : (throughputHis.length > 0 ? throughputHis[throughputHis.length - 1] : 0)
        const energy = i < powerHis.length ? (powerHis[i] / 1000) : (powerHis.length > 0 ? (powerHis[powerHis.length - 1] / 1000) : 5) // 转换为kWh
        const efficiency = energy > 0 ? throughput / energy : 0
        
        timeData.value.push(timeLabel)
        throughputData.value.push(throughput)
        energyData.value.push(energy)
        efficiencyData.value.push(efficiency)
        
        console.log(`初始数据点 ${i}: 时间=${timeLabel}, 吞吐量=${throughput}, 能耗=${energy}, 能效=${efficiency}`)
      }
      
      console.log(`✅ 初始真实数据加载完成，数据点数量: ${timeData.value.length}`)
    } else {
      console.warn('⚠️ API返回数据为空，使用模拟数据作为备用')
      await loadInitialMockData(maxAvailablePoints)
    }
  } catch (error) {
    console.error('❌ 获取初始数据失败，使用模拟数据作为备用:', error)
    await loadInitialMockData(maxAvailablePoints)
  }
  
  // 启动定时更新（每分钟更新一次）
  startDataUpdate()
  
  // 响应式处理
  window.addEventListener('resize', handleResize)
  
  // 初始化合并图表
  initCombinedChart()
  
  console.log('✅ 图表初始化完成')
}

// 加载初始模拟数据（作为备用）
const loadInitialMockData = async (maxAvailablePoints: number) => {
  console.log('加载初始模拟数据...')
  
  // 获取当前时间，生成过去的数据
  const now = new Date()
  const currentMinute = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), 0, 0)
  
  for (let i = maxAvailablePoints - 1; i >= 0; i--) {
    // 生成过去的整分钟时间
    const pastTime = new Date(currentMinute.getTime() - i * 60 * 1000) // 减去i分钟
    const timeStr = pastTime.toLocaleTimeString()
    
    // 生成模拟数据
    const throughput = 2 + Math.random() * 3
    const energy = 5 + Math.random() * 0.5
    const efficiency = throughput / energy
    
    timeData.value.push(timeStr)
    throughputData.value.push(throughput)
    energyData.value.push(energy)
    efficiencyData.value.push(efficiency)
    
    await new Promise(resolve => setTimeout(resolve, 10)) // 减少延迟
  }
  
  console.log(`模拟数据加载完成，数据点数量: ${timeData.value.length}`)
}

// 处理窗口大小变化
const handleResize = () => {
  if (displayMode.value === 'combined' && chartInstance) {
    chartInstance.resize()
  } else if (displayMode.value === 'separated') {
    throughputChartInstance?.resize()
    energyChartInstance?.resize()
    efficiencyChartInstance?.resize()
  }
}

// 组件挂载
onMounted(() => {
  initChart()
})

// 组件卸载
onUnmounted(() => {
  if (dataTimer) {
    clearInterval(dataTimer)
  }
  
  if (initialTimer) {
    clearTimeout(initialTimer)
  }
  
  if (syncTimeout) {
    clearTimeout(syncTimeout)
  }
  
  // 清理合并图表
  if (chartInstance) {
    chartInstance.off('dataZoom')
    chartInstance.dispose()
  }
  
  // 清理独立图表
  if (throughputChartInstance) {
    throughputChartInstance.off('dataZoom')
    throughputChartInstance.off('datazoom')
    throughputChartInstance.dispose()
  }
  if (energyChartInstance) {
    energyChartInstance.off('dataZoom')
    energyChartInstance.off('datazoom')
    energyChartInstance.dispose()
  }
  if (efficiencyChartInstance) {
    efficiencyChartInstance.off('dataZoom')
    efficiencyChartInstance.off('datazoom')
    efficiencyChartInstance.dispose()
  }
  
  window.removeEventListener('resize', handleResize)
})

// 监听显示模式变化
watch(() => displayMode.value, (newMode) => {
  // 确保在DOM更新后再执行
  setTimeout(() => {
    if (newMode === 'combined') {
      initCombinedChart()
    } else {
      initSeparatedCharts()
    }
  }, 50)
})
</script>

<template>
  <div class="overview-container">
    <div class="header">
      <h2>基站监控总览</h2>
      <div class="stats">
        <div class="stat-item">
          <span class="label">当前平均吞吐量:</span>
          <span class="value throughput">{{ throughputData[throughputData.length - 1]?.toFixed(2) || '--' }} Mbps</span>
        </div>
        <div class="stat-item">
          <span class="label">当前能耗:</span>
          <span class="value energy">{{ energyData[energyData.length - 1]?.toFixed(2) || '--' }}kWh</span>
        </div>
        <div class="stat-item">
          <span class="label">当前能效比:</span>
          <span class="value efficiency">{{ efficiencyData[efficiencyData.length - 1]?.toFixed(3) || '--' }}</span>
        </div>
      </div>
    </div>
    
    <div class="chart-container">
      <div class="chart-controls-top">
        <div class="chart-controls">
          <button 
            @click="toggleDisplayMode" 
            class="mode-btn"
            :class="{ active: displayMode === 'combined' }"
          >
            📊 合并图表
          </button>
          <button 
            @click="toggleDisplayMode" 
            class="mode-btn"
            :class="{ active: displayMode === 'separated' }"
          >
            📈 独立图表
          </button>
          <button 
            @click="updateData" 
            class="mode-btn"
            style="margin-left: 10px;"
          >
            🔄 刷新数据
          </button>
          <!-- <button 
            @click="addTestData" 
            class="mode-btn"
            style="margin-left: 10px; background: #52c41a;"
            title="添加测试数据点"
          >
            ➕ 添加数据点
          </button> -->
          <button 
            @click="resetZoomToDefault" 
            class="mode-btn"
            style="margin-left: 10px; background: #1890ff;"
            title="重置到默认15分钟视图"
            v-if="zoomState.userModified"
          >
            🔄 重置视图
          </button>
        </div>
        
        <!-- 历史数据查看控件 -->
        <div class="history-controls">
          <button 
            @click="toggleHistoryMode" 
            class="mode-btn history-btn"
            :class="{ active: isHistoryMode }"
          >
            {{ isHistoryMode ? '📈 实时模式' : '📚 历史模式' }}
          </button>
          
          <div v-if="isHistoryMode" class="hour-selector">
            <label for="hour-select">选择小时:</label>
            <select 
              v-if="getAvailableHours().length > 0"
              id="hour-select"
              v-model="selectedHour" 
              @change="selectHistoryHour(selectedHour)"
              class="hour-select"
            >
              <option 
                v-for="hour in getAvailableHours()" 
                :key="hour.value" 
                :value="hour.value"
              >
                {{ hour.label }}
              </option>
            </select>
            <span v-else class="no-history-tip">
              暂无可用的历史数据（需要至少一个完整小时）
            </span>
          </div>
        </div>
      </div>
      
      <!-- 图表区域 -->
      <!-- 合并图表 -->
      <div v-if="displayMode === 'combined'" ref="chartRef" class="chart" key="combined"></div>
      
      <!-- 独立图表 -->
      <div v-if="displayMode === 'separated'" class="separated-charts" key="separated">
        <div class="chart-row">
          <div ref="throughputChartRef" class="mini-chart" key="throughput"></div>
          <div ref="energyChartRef" class="mini-chart" key="energy"></div>
        </div>
        <div class="chart-row">
          <div ref="efficiencyChartRef" class="mini-chart full-width" key="efficiency"></div>
        </div>
      </div>
    </div>
    
    <!-- <div class="info">
      <p>💡 提示：</p>
      <ul>
        <li>数据每分钟在整分钟时从后端API自动更新（与API数据粒度一致）</li>
        <li>实时模式默认显示最近15分钟数据，最多可查看60分钟历史数据</li>
        <li>0点-1点之间数据量受限于当前时间（如00:30只能查看30分钟数据）</li>
        <li>平均吞吐量单位：Mbps，显示reg_aver_throughput_his数据</li>
        <li>能耗单位：kWh，显示total_power_his数据（原始数据除以1000）</li>
        <li>能效比：平均吞吐量/能耗的比值，单位：Mbps/kWh</li>
        <li>历史模式：可查看当天任意小时的完整数据，此时停止实时更新</li>
        <li>手动调整图表缩放后，可点击"🔄 重置视图"回到默认15分钟视图</li>
        <li>点击"➕ 添加数据点"可立即添加测试数据观察效果</li>
        <li>如果API请求失败，会自动回退到模拟数据</li>
        <li>初始化时会先显示模拟数据，然后逐步更新为真实数据</li>
        <li>时间轴每30秒显示一个时间标签</li>
        <li>支持两种显示模式：合并图表和独立图表</li>
        <li>合并图表：所有指标在一个图中显示，便于对比</li>
        <li>独立图表：每个指标单独显示，更加清晰</li>
        <li>图表默认显示最近1分钟的数据，自动平滑滚动</li>
        <li>手动调整缩放后，会保持您的设置，不再自动滚动</li>
        <li>点击"回到最新"按钮可恢复自动滚动到最新数据</li>
        <li>可以使用鼠标滚轮或下方滑块进行缩放</li>
        <li>独立图表模式下，缩放操作会同步到所有图表</li>
        <li>拖拽图表可查看历史数据</li>
      </ul>
    </div> -->
  </div>
</template>

<style scoped>
.overview-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.stats {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  font-size: 18px;
  font-weight: 600;
}

.value.throughput {
  color: #5470c6;
}

.value.energy {
  color: #fc8452;
}

.value.efficiency {
  color: #91cc75;
}

.chart-container {
  margin: 20px 0;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  overflow: hidden;
  position: relative;
}

.chart-controls-top {
  background: #f8f9fa;
  padding: 10px 15px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-controls {
  display: flex;
  gap: 5px;
}

.mode-btn {
  background: #fff;
  color: #666;
  border: 1px solid #ddd;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
}

.mode-btn:hover {
  background: #e6f7ff;
  border-color: #5470c6;
}

.mode-btn.active {
  background: #5470c6;
  color: white;
  border-color: #5470c6;
}

/* 历史控件样式 */
.history-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.history-btn {
  background: #fff3cd;
  border-color: #ffeeba;
  color: #856404;
}

.history-btn:hover {
  background: #fff3cd;
  border-color: #ffc107;
}

.history-btn.active {
  background: #ffc107;
  color: white;
  border-color: #ffc107;
}

.hour-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.hour-selector label {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}

.hour-select {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
  background: white;
  cursor: pointer;
  min-width: 120px;
}

.hour-select:focus {
  outline: none;
  border-color: #5470c6;
  box-shadow: 0 0 0 2px rgba(84, 112, 198, 0.2);
}

.no-history-tip {
  font-size: 12px;
  color: #999;
  font-style: italic;
}

.reset-btn {
  background: #5470c6;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.reset-btn:hover {
  background: #4c63d2;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.reset-btn:active {
  transform: translateY(0);
}

.chart {
  width: 100%;
  height: 500px;
}

.separated-charts {
  padding: 15px;
  background: #fff;
}

.chart-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-row:last-child {
  margin-bottom: 0;
}

.mini-chart {
  flex: 1;
  height: 300px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  background: #fff;
}

.mini-chart.full-width {
  width: 100%;
}

.info {
  margin-top: 20px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 6px;
  border-left: 4px solid #5470c6;
}

.info p {
  margin: 0 0 10px 0;
  color: #666;
  font-weight: 600;
}

.info ul {
  margin: 0;
  padding-left: 20px;
  color: #666;
}

.info li {
  margin-bottom: 5px;
}

@media (max-width: 768px) {
  .overview-container {
    padding: 15px;
  }
  
  .stats {
    gap: 15px;
  }
  
  .stat-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .chart {
    height: 400px;
  }
  
  .chart-controls-top {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .chart-controls {
    justify-content: center;
  }
  
  .reset-btn {
    align-self: center;
  }
  
  .chart-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .mini-chart {
    height: 250px;
  }
}
</style>
